package com.zjhn.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjhn.ds.common.BizResult;
import com.zjhn.ds.common.PageBean;
import com.zjhn.ds.common.PageResult;
import com.zjhn.ds.domain.dto.pc.SpinnerDto;
import com.zjhn.ds.domain.dto.pc.WorkShopStationDto;
import com.zjhn.ds.domain.dto.pc.WorkshopClassDto;
import com.zjhn.ds.domain.dto.pc.WorkshopDto;
import com.zjhn.ds.domain.entity.jlw.Spinner;
import com.zjhn.ds.domain.entity.jlw.Station;
import com.zjhn.ds.domain.entity.jlw.Workshop;
import com.zjhn.ds.domain.entity.jlw.WorkshopClasses;
import com.zjhn.ds.domain.vo.OperatorVo;
import com.zjhn.ds.mapper.*;
import com.zjhn.ds.param.AddUpdateClassParam;
import com.zjhn.ds.param.AddUpdateWorkshopParam;
import com.zjhn.ds.param.BindSpinnerParam;
import com.zjhn.ds.param.WorkshopRelPageParam;
import com.zjhn.ds.service.WorkshopService;
import com.zjhn.ds.utils.base.DateUtil;
import com.zjhn.ds.utils.CommonUtil;
import com.zjhn.ds.utils.EntityTransformUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.service.impl
 * @Author: sxt
 * @CreateTime: 2023-09-07  14:04
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Service
public class WorkshopServiceImpl implements WorkshopService {

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private EntityTransformUtil entityTransformUtil;

    @Resource
    private WorkshopMapper workshopMapper;

    @Resource
    private SpinnerMapper spinnerMapper;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private WorkshopClassesMapper workshopClassesMapper;

    /**
     * 新增车间
     * @param param
     * @return
     */
    @Override
    public BizResult<?> addUpdate(AddUpdateWorkshopParam param) {
        Workshop workshop;
        if (StringUtils.isBlank(param.getWorkshopId())) {
            // 新增
            workshop = workshopMapper.selectOne(new QueryWrapper<Workshop>().eq("name", param.getName()));
            if (workshop != null)
                return BizResult.fail("车间名称已存在");

            workshop = Workshop.builder()
                    .name(param.getName())
                    .directorId(param.getDirectorId())
                    .columnNumber(param.getColumnNumber())
                    .lineNumber(param.getLineNumber())
                    .build();
            workshopMapper.insert(workshop);
        } else {
            workshop = workshopMapper.selectById(param.getWorkshopId());
            if (workshop == null)
                return BizResult.fail("车间不存在");

            workshop.setName(param.getName());
            workshop.setDirectorId(param.getDirectorId());
            workshop.setLineNumber(param.getLineNumber());
            workshop.setColumnNumber(param.getColumnNumber());
            workshopMapper.updateById(workshop);
        }
        commonUtil.updateWorkshopInfo(workshop.getId(),workshop.getName());
        return BizResult.success();
    }

    /**
     * 删除 车间
     *
     * @param workshopId
     * @return
     */
    @Override
    public BizResult<?> delete(String workshopId) {
        Workshop workshop = workshopMapper.selectById(workshopId);
        if (workshop == null)
            return BizResult.success();

        Integer spinnerCount = spinnerMapper.selectCount(new QueryWrapper<Spinner>().eq("workshop_id", workshopId));
        if (spinnerCount > 0)
            return BizResult.fail("当前车间已绑定挡车工，请清空后再进行删除");
        Integer stationCount = stationMapper.selectCount(new QueryWrapper<Station>().eq("workshop_id", workshopId));
        if (stationCount > 0)
            return BizResult.fail("当前车间已绑定工位，请清空后再进行删除");

        workshopMapper.deleteById(workshopId);
        commonUtil.removeWorkshopInfo(workshopId);
        return BizResult.success();
    }

    /**
     * 分页查询车间信息
     *
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<WorkshopDto>> page(PageBean param) {
        IPage<Workshop> page = workshopMapper
                .selectPage(
                        new Page<>(param.getCurrent(), param.getSize()),
                        new QueryWrapper<Workshop>().orderByAsc("create_time")
                );

        // 对象转化
        IPage<WorkshopDto> convert = page.convert(c -> {
            WorkshopDto build = WorkshopDto.builder().build();
            BeanUtils.copyProperties(c, build);
            build.setWorkshopId(c.getId());
            build.setCreateTime(DateUtil.formatDateToString(c.getCreateTime()));
            if (StringUtils.isNotBlank(c.getDirectorId())) {
                build.setDirectorId(c.getDirectorId());
                build.setDirector(commonUtil.getOperatorById(c.getDirectorId()).getRealName());
            }
            return build;
        });

        return BizResult.success(PageResult.<WorkshopDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .total(convert.getTotal())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 分页查询车间挡车工信息
     *
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<SpinnerDto>> spinnerPage(WorkshopRelPageParam param) {
        IPage<Spinner> page = spinnerMapper.selectPage(
                new Page<>(param.getCurrent(), param.getSize()),
                new QueryWrapper<Spinner>().eq("workshop_id", param.getWorkshopId()).orderByAsc("create_time"));

        IPage<SpinnerDto> convert = page.convert(c -> {
            SpinnerDto build = SpinnerDto.builder().build();
            OperatorVo operator = commonUtil.getOperatorById(c.getOperateId());
            build.setSpinnerId(c.getId());
            build.setUsername(operator.getUsername());
            build.setUserNo(operator.getUserNo());
            build.setRealName(operator.getRealName());
            build.setDepartment(commonUtil.getDepartment(operator.getDepartmentGuid()));
            build.setCreateTime(DateUtil.formatDateToString(c.getCreateTime()));
            return build;
        });

        return BizResult.success(PageResult.<SpinnerDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .total(convert.getTotal())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 车间删除挡车工
     * @param spinnerId
     * @return
     */
    @Override
    public BizResult<?> removeSpinner(String spinnerId) {
        spinnerMapper.deleteById(spinnerId);
        return BizResult.success();
    }

    /**
     * 车间绑定挡车工
     * @param param
     * @return
     */
    @Override
    public BizResult<?> bindSpinner(BindSpinnerParam param) {
        Spinner spinner = spinnerMapper.selectOne(new QueryWrapper<Spinner>().eq("operate_id", param.getOperateId()));
        if (spinner != null)
            return BizResult.fail("挡车工已绑定在其他车间下");

        spinner = Spinner.builder()
                .workshopId(param.getWorkshopId())
                .operateId(param.getOperateId())
                .build();
        spinnerMapper.insert(spinner);
        return BizResult.success();
    }

    /**
     * 分页查询车间工位信息
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<WorkShopStationDto>> stationPage(WorkshopRelPageParam param) {
        IPage<Station> page = stationMapper.selectPage(
                new Page<>(param.getCurrent(), param.getSize()),
                new QueryWrapper<Station>().eq("workshop_id", param.getWorkshopId()).orderByAsc("line_number","column_number","station_code")
        );

        IPage<WorkShopStationDto> convert = entityTransformUtil.workshopStationDtoChange(page);

        return BizResult.success(PageResult.<WorkShopStationDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .total(convert.getTotal())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 获取车间班次时间表
     * @param workshopId
     * @return
     */
    @Override
    public BizResult<List<WorkshopClassDto>> getWorkshopClass(String workshopId) {
        List<WorkshopClasses> workshopClasses = workshopClassesMapper.selectList(
                new QueryWrapper<WorkshopClasses>().eq("workshop_id", workshopId).orderByAsc("start_time"));

        List<WorkshopClassDto> res = new ArrayList<>();
        if (workshopClasses.size() > 0) {
            res.addAll(workshopClasses.stream()
                    .map(c -> WorkshopClassDto.builder()
                            .workshopClassId(c.getId())
                            .workshopClassName(c.getName())
                            .startTime(c.getStartTime())
                            .endTime(c.getEndTime())
                            .build()).collect(Collectors.toList()));
        }

        return BizResult.success(res);
    }

    /**
     * 车间删除班次
     * @param workshopClassId
     * @return
     */
    @Override
    public BizResult<?> removeWorkshopClass(String workshopClassId) {
        workshopClassesMapper.deleteById(workshopClassId);
        return BizResult.success();
    }

    /**
     * 新增/修改车间班次信息
     * @param param
     * @return
     */
    @Override
    public BizResult<?> addUpdateClass(AddUpdateClassParam param) {
        WorkshopClasses workshopClasses;
        if (StringUtils.isNotBlank(param.getWorkshopClassId())) {
            // 更新
            workshopClasses = workshopClassesMapper.selectById(param.getWorkshopClassId());
            if (workshopClasses == null)
                return BizResult.fail("班次不存在");
            workshopClasses.setName(param.getWorkshopClassName());
            workshopClasses.setStartTime(param.getStartTime());
            workshopClasses.setEndTime(param.getEndTime());
            workshopClassesMapper.updateById(workshopClasses);
        } else {
            // 新增
            workshopClasses = WorkshopClasses.builder()
                    .workshopId(param.getWorkshopId())
                    .name(param.getWorkshopClassName())
                    .startTime(param.getStartTime())
                    .endTime(param.getEndTime())
                    .build();
            workshopClassesMapper.insert(workshopClasses);
        }

        return BizResult.success();
    }

}
